/**
 * desc: gulp configuration for angular@1.x
 * author: Joe
 * date: 7/5/2018
 */

var gulp = require('gulp');
var pump = require('pump');
var rename = require('gulp-rename');
var userref = require('gulp-useref');
var rev = require('gulp-rev');
var revreplace = require('gulp-rev-replace');
var replace = require('gulp-replace');
var gulpif = require('gulp-if');
var inject = require('gulp-inject');
var zip = require('gulp-zip');
var del = require('del');

var htmlmin = require('gulp-html-minify');
var templatecache = require('gulp-angular-templatecache');
var stripdebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var cssmin = require('gulp-cssmin');
// var autoprefixer = require('gulp-autoprefixer');
var autoprefixer = require('autoprefixer');
var postcss = require('gulp-postcss');
var customprop = require('postcss-custom-properties');
var imagemin = require('gulp-imagemin');

var projectinfo = require('./package.json');

/**
 * compile conf
 */
var root = 'src/';
var dist = 'dist/';
var path = {
  doc: [root + 'doc/*.{doc,docx}', dist],
  config: [root + '*.json', dist],
  entry: [root + 'index.html', dist],
  views: [root + 'views/**/*.html', dist + 'js/'],
  components: [root + 'components/**/*.html', dist + 'js/'],
  assets: [root + '**/*.{png,jpg,jpeg,gif,bmp,ico,svg}', dist + 'assets/'],
  plugins: ['plugins/', dist + 'plugins/'],
};

/**
 * task definition
 */
// doc
gulp.task('doc', function(cb) {
  pump([
    gulp.src(path.doc[0]),
    gulp.dest(path.doc[1]),
  ], cb);
});

// config
gulp.task('config', function(cb) {
  pump([
    gulp.src(path.config[0]),
    gulp.dest(path.config[1]),
  ], cb);
});

// entry
gulp.task('entry', function(cb) {
  var cssCondition = function (file) {
    var path = file.path;
    return path.indexOf('css') > -1 && path.indexOf('ref') === -1;
  };

  pump([
    gulp.src(path.entry[0]),
    userref(),
    rev(),
    revreplace(),
    gulpif('*.js', uglify()),
    gulpif(cssCondition, cssmin()),
    inject(gulp.src(path.views[1] + '*-templates.js'),
      {starttag: '<!--inject:templates-->', relative: false}),
    replace(/(\/dist\/|\.{2}\/)/g, ''),
    gulpif('*.html', htmlmin()),
    rename(function(path) {
      if (path.extname === '.html') {
        path.basename = path.basename.split('-')[0];
      }
    }),
    gulp.dest(path.entry[1]),
  ], cb);
});

// views
gulp.task('views', function(cb) {
  pump([
    gulp.src(path.views[0]),
    replace(/<img.*?(?:>|\/>)/gi, function($0) {
      var src = $0.match(/[^:]src=['"]?([^'"]*)['"]?/i);
      if (src) {
        var index = src[0].lastIndexOf('/');
        if (index > -1) {
          $0 = $0.replace(src[0], ' src="assets' + src[0].substr(index));
        }
      }
      return $0;
    }),
    templatecache({filename: 'views-templates.js', module: 'app', root: 'views'}),
    gulp.dest(path.views[1]),
  ], cb);
});

// components
gulp.task('components', function(cb) {
  pump([
    gulp.src(path.components[0]),
    replace(/<img.*?(?:>|\/>)/gi, function($0) {
      var src = $0.match(/[^:]src=['"]?([^'"]*)['"]?/i);
      if (src) {
        var index = src[0].lastIndexOf('/');
        if (index > -1) {
          $0 = $0.replace(src[0], ' src="assets' + src[0].substr(index));
        }
      }
      return $0;
    }),
    templatecache({filename: 'component-templates.js', module: 'app', root: 'components'}),
    gulp.dest(path.components[1]),
  ], cb);
});

// assets
gulp.task('assets', function(cb) {
  pump([
    gulp.src(path.assets[0]),
    rename({dirname: ''}),
    imagemin({
      optimizationLevel: 5,
    }),
    gulp.dest(path.assets[1]),
  ], cb);
});

// plugins
gulp.task('plugins', function(cb) {
  pump([
    gulp.src(path.plugins[0] + '**'),
    gulp.dest(path.plugins[1]),
  ], cb);
});

// rewrite
gulp.task('re:js', function(cb) {
  pump([
    gulp.src([dist + 'js/*.js', '!' + dist + 'js/template.js']),
    stripdebug(),
    gulp.dest(dist + 'js/'),
  ], cb);
});
gulp.task('re:css', function(cb) {
  pump([
    gulp.src(dist + 'css/*.css'),
    // autoprefixer(),
    postcss([autoprefixer(), customprop()]),
    replace(/url\(([0-9a-zA-Z-_.\/]*)\)/g, function($0, $1) {
      var match = $1.replace(/['"]/g, '');
      var index = match.lastIndexOf('/');
      if (index > -1) {
        $1 = '../assets' + match.substr(index);
      }
      return 'url(' + $1 + ')';
    }),
    gulp.dest(dist + 'css/'),
  ], cb);
});

// zip
gulp.task('zip', function(cb) {
  var now = new Date();
  var month = now.getMonth() + 1;
  var date = now.getDate();
  var timeTail = (month < 10 ? '0' + month : month) + '-' +
    (date < 10 ? '0' + date : date);
  pump([
    gulp.src(dist + '**'),
    // gulp.src([dist + '**', '!' + dist + '**/*.zip']),
    zip(projectinfo.name + '@v' + projectinfo.version + '_' + timeTail +
      '.zip'),
    gulp.dest(dist),
  ], cb);
});

// clean
gulp.task('clean', function(cb) {
  del.sync(dist);
  cb();
});

// default
gulp.task('default', gulp.series('clean', gulp.parallel('doc',
  gulp.series('config', 'views', 'components', 'entry', gulp.parallel('re:js', 're:css')), 'assets', 'plugins'),
  'zip'));
